package com.homegoods.app;

import android.app.Application;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;

import com.homegoods.BuildConfig;
import com.homegoods.integration.AppLifecycles;
import com.homegoods.integration.ConfigModule;
import com.tencent.bugly.crashreport.CrashReport;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;

/**
 * @author QiQi
 * @ClassName: AppConfig
 * @date 2018/10/23
 * @description
 */
public class AppConfig implements ConfigModule {
    @Override
    public void applyOptions(Context context) {

    }

    @Override
    public void injectAppLifecycle(Context context, List<AppLifecycles> lifecycles) {
        lifecycles.add(new AppLifecycles() {
            @Override
            public void attachBaseContext(@NonNull Context base) {
            }

            private String getProcessName(int pid) {
                BufferedReader reader = null;
                try {
                    reader = new BufferedReader(new FileReader("/proc/" + pid + "/cmdline"));
                    String processName = reader.readLine();
                    if (!TextUtils.isEmpty(processName)) {
                        processName = processName.trim();
                    }
                    return processName;
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (reader != null) {
                            reader.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                return null;
            }

            @Override
            public void onCreate(@NonNull Application application) {
                String packageName = application.getPackageName();
                String processName = getProcessName(android.os.Process.myPid());
                CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(application);
                strategy.setUploadProcess(processName == null || processName.equals(packageName));

                CrashReport.initCrashReport(application, "d45697e499", BuildConfig.DEBUG, strategy);
            }

            @Override
            public void onTerminate(@NonNull Application application) {

            }
        });
    }

    @Override
    public void injectActivityLifecycle(Context context, List<Application.ActivityLifecycleCallbacks> lifecycles) {

    }

    @Override
    public void injectFragmentLifecycle(Context context, List<FragmentManager.FragmentLifecycleCallbacks> lifecycles) {

    }
}
